package com.rexolar.openapi.utlis;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * IpAddressUtil
 *
 * @author zhusiyu
 **/

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class IpAddressUtil {

    private static final String UNKNOW_IP = "unknow";

    public static String getIpAddr(HttpServletRequest request) {

//        String ipAddress = request.getHeader("X-Real-IP");
//        if (StringUtils.isBlank(ipAddress) || UNKNOW_IP.equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getHeader("X-Forwarded-For");
//        }
//
//        if (StringUtils.isBlank(ipAddress) || UNKNOW_IP.equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getHeader("Proxy-Client-IP");
//        }
//        if (StringUtils.isBlank(ipAddress) || UNKNOW_IP.equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (StringUtils.isBlank(ipAddress) || UNKNOW_IP.equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getRemoteAddr();
//        }


        String ipAddress = request.getHeader("X-Forwarded-For");

        if (StringUtils.isBlank(ipAddress) || UNKNOW_IP.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        String ipSeparate = ",";
        int ipLength = 15;
        if (StringUtils.isNotBlank(ipAddress) && ipAddress.length() > ipLength && ipAddress.contains(ipSeparate)) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(ipSeparate));
        }
        return ipAddress;
    }
}
